import { onMounted, ref } from 'vue';
import { cancelOrder, deleteOrder, followOrUnfollow, getPrescriptionPic } from '@/services/consult';
import type { ConsultOrderItem, FollowType } from '@/types/consult';
import { showFailToast, showImagePreview, showSuccessToast } from 'vant';
import { OrderType } from '@/enums';
import type { OrderDetail } from '@/types/order';
import { getMedicalOrderDetail } from '@/services/order';

// Vue3 概念：通过组合式API封装 数据逻辑 在一起的函数 组合式函数 useXxxx
// composables
export const  useFollow =(type:FollowType ='doc' )=> {
  const loading = ref(false);
  const follow = async (item: {id:string,likeFlag:0|1}) => {
    loading.value = true;
    try {
      await followOrUnfollow(item.id,type);
      item.likeFlag = item.likeFlag === 1 ? 0 : 1;

    } finally {
      loading.value = false;
    }
  };
  return { loading, follow };
}

// 提供查看处方的逻辑

export const useShowPrescription = ()=>{
  const onShowPrescription = async(id?:string)=>{
    if(id){
      const res = await getPrescriptionPic(id)
      showImagePreview([res.data.url])
    }
  }
  return {onShowPrescription}
}

// 取消订单
export const useCancelOrder = ()=>{
  const loading =ref(false)
  const cancelConsultOrder = async(item:ConsultOrderItem)=>{
    try{
      loading.value = true
      await cancelOrder(item.id)
      item.status = OrderType.ConsultCancel
      item.statusValue = '已取消'
      showSuccessToast('取消成功')
    }catch(error){
      showFailToast('取消失败')
      console.log(error)
    }finally{
      loading.value = false
    }
  }
  return { loading,cancelConsultOrder}
}

// 删除订单
export const useDeleteOrder = (cb:()=>void)=>{
  const loading = ref(false)
  const deleteConsultOreder = async(item:ConsultOrderItem)=>{
    try {
      loading.value = true
      await deleteOrder(item.id)
      showSuccessToast('删除成功')
      // emit('on-delete',item.id)
      // cb && cb()
      if(cb) cb ()
    } catch (error) {
      showFailToast('删除订单失败')
      console.log(error)
    }finally{
      loading.value =false
    }
  }
  return {loading,deleteConsultOreder}
}

export const useOrderDetail = (id:string)=>{
  const order = ref<OrderDetail>()
  const loading = ref(false)
  onMounted(async()=>{
    try{
      loading.value = true
      const res = await getMedicalOrderDetail(id as string)
      order.value = res.data
    }finally{
      loading.value = false
    }
  })
  return {loading,order}
}
